package titt.io.util.wrap;

import titt.head.HTTPHead;
import titt.io.socket.out.TITTOutputStream;
import titt.service.content.NuderContent;
import titt.service.content.NuderRequest;
import titt.service.content.NuderResponse;
import titt.util.io.pipe.PipeListener;

public class NuderContentWrapper implements Wrapper {

	private NuderContent get(Object o) {
		return (NuderContent)o;
	}
	
	@Override
	public int getLength(Object o) {
		return get(o).getLength();
	}

	@Override
	public String getMimeType(Object o) {
		HTTPHead head = o instanceof NuderRequest? ((NuderRequest)o).getContentHead() : ((NuderResponse)o).getResponseHead();
		return head.getHeader("Content-Type").getValue();
	}

	@Override
	public boolean supports(Object o) {
		return o instanceof NuderRequest || o instanceof NuderResponse;
	}

	@Override
	public void writeTo(PipeListener listener, TITTOutputStream out, Object o) throws Exception {
		try {
			get(o).writeToStream(out, listener);
		}
		catch(Exception e) {
			get(o).getContentStream().close();
			throw e;
		}
	}

}
